package filter;

import net.sf.json.JSONObject;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import utils.PowerUtil;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class SecurityFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String path = req.getRequestURI();
        String ss = req.getRequestURL().toString();
        String servletPath = req.getServletPath();
        HttpSession session  = req.getSession();
        /**
         * 2018-4-8添加，关于接口调用的部分直接放行
         */
        if(isLoginRequest(path) 
        		|| isNoCheckRequest(path) 
        		||isReourceFile(path)
        		||isUnCheckWsRequest(path,session)){
        	 chain.doFilter(request, response);
        	 return;
        }
        //System.out.println("is Not loginRequest ||isNoCheckRequest ||isReourceFile  ||isUnCheckWsRequest");
      
        // 判断是否登录
        if (session.getAttribute("userId") == null) {
            // 重定向到登录页面
            res.sendRedirect(req.getContextPath() + "/login.do");
            //System.out.println("/login.html");
        	}
        else {
            String user_code = (String) session.getAttribute("userCode");
           
            if(user_code==null){
                res.sendRedirect(req.getContextPath() + "/login.do");
                //System.out.println("2 /login.html");
            }else{
            	 if(!haseUrlPermission(req.getRequestURI(), user_code)){
                    res.sendRedirect(req.getContextPath() + "/security/security.do");
                    return;
           			 }
//                String[] userCode = user_code.split("#");
//                for(int i=0;i< userCode.length;i++){
//                    ArrayList<String> powerList = PowerUtil.pickPower(userCode[i]);
//                    if((powerList.contains(path))||(powerList.contains(servletPath))){
//                        chain.doFilter(request, response);
//                        return;
//                    	}
//                	 }
                chain.doFilter(request, response);
                //System.out.println("2 not login login.html");
                //comment By xuwenyuan 2018/08/22 start
                //String referer =  req.getHeader("referer");
                //res.sendRedirect(referer);
                //comment By xuwenyuan 2018/08/22 end
                return;
             	}
        	}
    }
    @Override
    public void destroy() {
    }
    
    private boolean isReourceFile(String path){
    	if(path.contains(".js")
    			||path.contains(".css")
    			||path.contains(".png")
    			||path.contains(".gif")
    			||path.contains(".jpg")
    			||path.contains(".bmp")
    			||path.contains(".ico")
    			||path.contains(".ico2")
    			||path.contains(".woff")
    			||path.contains(".woff2")
    			||path.contains(".less")
    			||path.contains(".chart")
    			||path.contains(".eot"))
    		return true;
    	return false;
    }
   private boolean isLoginRequest(String path){
	   if(path.contains("login")
   			||path.contains("LoginServlet"))
   		return true;
   	return false;
   }
   private boolean isNoCheckRequest(String path){
	   if(path.contains("DownloadServlet")
			  // ||path.contains("conf")
			   )
	   		return true;
	   return false;
   }
   private boolean isUnCheckWsRequest(String path,HttpSession session){
	   if(path.contains("/ws/job")
			   ||path.contains("/ws/model")
			   ||path.contains("/ws/task")
			   ||path.contains("/ws/algorithm")
			   ||path.contains("/ws/source")
			   ||path.contains("/ws/remote")
			   ){
//		   System.out.println("wsssssss:"+path)
		   if ((!path.contains("/ws/source"))&& (!path.contains("/ws/remote"))||session.getAttribute("userId") == null) {
//		   if ( session.getAttribute("userId") == null ||session.getAttribute("userId") == "") {
               session.setAttribute("userId", "-1");
           	}
	   	return true;
	   	}
	   return false;
   }
   @SuppressWarnings("null")
private boolean haseUrlPermission(String url, String userCode) {
		//System.out.println(url);
		//System.out.println(userCode);
		if(userCode==null)return false;
		if(url!=null)return true;
		if(url.contains(".html")){
			
			if( url.contains("index.html"))
					return true;
			if(userCode.contains( "1001"))
				if( (url.contains( "algorithmList.html") ) 
					 || (url.contains( "algorithmRegister.html") )
					 || (url.contains( "algorithmXMLRegister.html") ))
					return true;
			if(userCode.contains( "1002"))
				if( (url.contains( "modelEdit.html") ) 
					 || (url.contains( "modelList.html") ))
						return true;
			if(userCode.contains( "1003"))
				if( (url.contains( "tasksList.html")) 
					 || (url.contains( "tasksHistoryList.html")))
						return true;
			if(userCode.contains( "1004"))
				if( (url.contains( "algorithm") )
					 || (url.contains( "usersManagement.html") )
					 || (url.contains( "allModelListChoiceByBatchTasks.html") )
					 || (url.contains( "task") )
					 || (url.contains( "Task") )
					 || (url.contains( "taskAlgorithmSettingByBatchTasks.html") )
					 || (url.contains( "taskStartSettingByBatchTasks.html") )
				    || (url.contains( "algorithmClassification.html")) //allModelListChoiceByBatchTasks.html taskEditByBatchTasks.html
				    || (url.contains( "logList.html")) )
			    	return true;
			if(userCode.contains( "1005"))
				if( (url.contains( "storage.html")) && (userCode.contains( "1005")))
					return true;
			if(userCode.contains( "1006"))
				if( (url.contains( "workRegister.html") )
					 || (url.contains( "workList.html") )
				    || (url.contains( "queueRegister.html") )
				    || (url.contains( "queueList.html") )
				    || (url.contains( "nodeRegister.html") )
				    || (url.contains( "nodeList.html") )
				    || (url.contains( "nodeClassification.html") )
				    || (url.contains( "gpuList.html") )
				    || (url.contains( "clusterMonitoring.html") ))
			    return true;
			
			return false;
		}
		return true;
	}
}